﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web.Services;
using System.Xml;
using log4net;
using log4net.Config;
using OrbitOne.Elmah.Logic;

namespace OrbitOne.Elmah.WebService
{
    /// <summary>
    /// The OrbitOne Elmah webservice. This service is responsible for processing all related agent =&gt; database requests.
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service : System.Web.Services.WebService
    {
        #region Static fields
        private static readonly ILog _logger = LogManager.GetLogger(typeof(Service));
        #endregion

        public Service()
        {
            FileInfo fileInfo = new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            XmlConfigurator.ConfigureAndWatch(fileInfo);
            _logger.Info("Service constructed");
        }

        #region WebMethods
        [WebMethod]
        public int LogError(string errorXml, Guid errorId)
        {
            _logger.Debug("Logging error : " + errorId);
            var orbitOneElmahErrorService = new OrbitOneElmahErrorService();
            return (int)orbitOneElmahErrorService.SaveError(errorXml, errorId);
        }

        [WebMethod]
        public int HeartbeatInterval()
        {
            return int.Parse(OrbitOneElmahConfiguration.Load().HeartbeatInterval);
        }

        [WebMethod, Obsolete("This method is obsolete, please use the HeartbeatInterval method.")]
        public int GetHeartBeatInterval()
        {
            return HeartbeatInterval();
        }

        [WebMethod, Obsolete("This method is obsolete, please use the SetHeartbeat method.")]
        public void OnHeartBeat(DateTime dateTime, string agentName)
        {
            try
            {
                _logger.Debug("OnHeartBeat : " + agentName);
                var agentService = new AgentService();
                var agent = agentService.Provider.Context.Agents.Where(a => a.Name == agentName).FirstOrDefault();
                if (agent == null)
                {
                    agent = new Data.Agent
                    {
                        Id = Guid.NewGuid(),
                        Name = agentName,
                        Description = agentName,
                        CreatedOn = dateTime,
                        IsActive = true
                    };

                }
                agent.LastHeartBeat = dateTime;
                agentService.Save(agent);

            }
            catch (Exception e)
            {
                _logger.Error(e);
            }
        }

        [WebMethod]
        public void SetHeartbeat(HeartbeatRequest request)
        {
            try
            {
                _logger.Debug("SetHeartbeat : " + request.Name);

                var agentService = new AgentService();
                var agent = agentService.GetByCreatedOn(request.CreatedOn, request.Name);
                if (agent == null || agent.Name != request.Name)
                {
                    agent = new Data.Agent
                                {
                                    Id = Guid.NewGuid(),
                                    CreatedOn = request.CreatedOn,
                                    IsActive = true,
                                    Name = request.Name
                                };
                }

                agent.LastHeartBeat = DateTime.Now;
                if (!string.IsNullOrEmpty(request.Description))
                {
                    if (request.Description != agent.Description)
                    {
                        agent.Description = request.Description;
                    }
                }
                agentService.Save(agent);
            }
            catch (Exception e)
            {
                _logger.Error(e);
            }
        }
        #endregion
    }
}